using System;
using System.Collections.Generic;
using System.Text;
using Musicman.Entities.BusinessEntities;
using System.Net.Mail;
using Musicman.Entities;
using Musicman.Business;
using System.IO;
using Gmailer;
using Musicman.Common;
using System.Net.Mime;

namespace Musicman.Business
{
    public class MailManager
    {
        # region singleton definition

        private MailSender mSender;
        static readonly MailManager instance = new MailManager();
        
        public static MailManager Instance
        {
            get
            {
                return instance;
            }
        }
        static MailManager()
        {
            instance.mSender = MailSender.Instance;
            instance.mSender.SendingFinished += new SendingFinishedHandler(instance.mSender_SendingFinished);
            instance.mSender.OnError += new SendingOnErroHandler(instance.mSender_OnError);
        }

        # endregion

        private void mSender_OnError(Exception ex)
        {
            LogManager.LogException("Error sending mail", ex);
        }

        private void mSender_SendingFinished(System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                LogManager.LogException("Error sending mail", e.Error);
            }
        }

        public void SendNotificationMail(SearchJobConfigurationElement job)
        {
            List<User> users = DataManager.Instance.GetMailingList();
            string mailTemplate = GetMailTemplate(AppDomain.CurrentDomain.BaseDirectory + "MailTemplate\\mail_template.htm");

            if (users != null && !String.IsNullOrEmpty(mailTemplate))
            {
                try
                {
                    MailMessage mail = new MailMessage();
                    for (int i = 0; i < users.Count; i++)
                    {
                        mail.To.Add(users[i].Emailaddress);
                    }
                    mailTemplate = String.Format(mailTemplate, DateTime.Now, job.Name, job.totalFiles, job.addedFiles, job.modifiedFiles, job.deletedFiles);
                    mail.Subject = String.Format("Musicman search ({0}) finished. {1}", job.Name, DateTime.Now);
                    mail.IsBodyHtml = true;
                    mail.From = new System.Net.Mail.MailAddress(AppSettingsHelper.GetWebConfigValue(Constants.Sendusername),
                                                                AppSettingsHelper.GetWebConfigValue(Constants.Displayname));
                    mail.Body = mailTemplate;
                    mSender.SendMail(mail);
                }
                catch (Exception ex)
                {
                    LogManager.LogException("Error sending mail", ex);
                }
            }
        }

        public void SendActivationMail(User user, string appServer)
        {

            string emailBody = @"Congratulation {0} {1}. You've almost finished your registration with your site.
To confirm your registration request follow the link below:

{2}Register.aspx?ACTIVATIONCODE={3}

... 

and afterwards you can log in with the following credentials
Email: {4}
Passwrod: {5}

Regards,
Musicman Levi9 team.
";
                try
                {
                    MailMessage mail = new MailMessage();
                    mail.Subject = "Activation mail";
                    mail.IsBodyHtml = false;
                    mail.From = new System.Net.Mail.MailAddress(AppSettingsHelper.GetWebConfigValue(Constants.Sendusername),
                                                    AppSettingsHelper.GetWebConfigValue(Constants.Displayname));
                    mail.To.Add(user.Emailaddress);
                    mail.Body = String.Format(emailBody, user.Firstname, user.Lastname, appServer, user.ActivationCode, user.Emailaddress, user.Password);
                    mSender.SendMail(mail);
                }
                catch (Exception ex)
                {
                    LogManager.LogException("Error sending mail", ex);
                }
        }

        private string GetMailTemplate(string filepath)
        {
            string res = "";
            if (File.Exists(filepath))
            {
                using (StreamReader sr = new StreamReader(File.Open(filepath, FileMode.Open, FileAccess.Read)))
                {
                    res = sr.ReadToEnd();
                    sr.Close();
                }
            }
            return res;
        }
    }
}
